<template>
  <!-- preset="card" -->
  <n-modal v-model:show="showModal" style="width: 800px; max-width: 90vw">
    <div class="model-container">
      <div class="model-content">
        <div class="model-title-box">
          <div class="icon-title-legend"></div>
          <div class="title-text">新建撤防作业</div>
          <div class="close-box" @click="showModal = false"></div>
        </div>
        <div class="content-box">
          <job-departure-form ref="formRef" />
        </div>
        <div class="btn-box">
          <n-button type="success" @click="handleSubmit">确定</n-button>
          <n-button type="info" @click="showModal = false">取消</n-button>
        </div>
      </div>
    </div>
  </n-modal>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import JobDepartureForm from './jobDepartureForm.vue';
  import { getTracksByOrgId } from '@/api/business/stationManager/track';
  import { getGroupList } from '@/api/home/group';
  import { getStationByOrgId } from '@/api/business/stationManager/station';
  import { addDefensiveTask } from '@/api/home/defensive';

  // 定义事件发射
  const emit = defineEmits<{
    (e: 'refresh'): void;
  }>();

  // 响应式数据
  const showModal = ref(false);
  const formRef = ref();
  const directionOptions = ref([]);
  const trackOptions = ref([]);
  const groupOptions = ref([]);
  let orgId = '';

  // 消息提示
  const message = useMessage();

  // 显示模态框
  function show(id: string) {
    return new Promise<void>(async (resolve) => {
      showModal.value = true;
      orgId = id;

      // 加载数据
      await loadDirectionOptions();
      await loadTrackOptions();
      await loadGroupOptions();

      // 设置表单数据
      formRef.value?.setFormData(
        { orgId: id },
        {
          directionOptions: directionOptions.value,
          trackOptions: trackOptions.value,
          groupOptions: groupOptions.value,
        }
      );

      resolve();
    });
  }

  // 加载方向选项
  async function loadDirectionOptions() {
    try {
      const res = await getStationByOrgId({ orgId });
      if (res && res.direction) {
        if (res.direction === '1') {
          directionOptions.value = [
            { value: res.directionEast, label: res.directionEast },
            { value: res.directionWest, label: res.directionWest },
          ];
        } else {
          directionOptions.value = [
            { value: res.directionSouth, label: res.directionSouth },
            { value: res.directionNorth, label: res.directionNorth },
          ];
        }
      }
    } catch (error) {
      console.error('加载方向选项失败:', error);
    }
  }

  // 加载股道选项
  async function loadTrackOptions() {
    try {
      const res = await getTracksByOrgId({
        currentPage: 1,
        pageSize: 999,
        orgId,
      });
      trackOptions.value = res.records || [];
    } catch (error) {
      console.error('加载股道选项失败:', error);
    }
  }

  // 加载班组选项
  async function loadGroupOptions() {
    try {
      const res = await getGroupList({
        currentPage: 1,
        pageSize: 999,
        orgId,
      });
      groupOptions.value = res.records || [];
    } catch (error) {
      console.error('加载班组选项失败:', error);
    }
  }

  // 处理表单提交
  async function handleSubmit() {
    try {
      const formData = await formRef.value?.submit();
      if (formData) {
        // 设置额外的表单数据
        formData.groupAndTaskList = formRef.value?.formChild;

        // 提交数据
        await addDefensiveTask(formData);

        // 关闭模态框并刷新数据
        showModal.value = false;
        message.success('撤防作业创建成功');
        emit('refresh');
      }
    } catch (error) {
      message.error('操作失败: ' + (error as Error).message);
    }
  }

  // 暴露方法给父组件
  defineExpose({
    show,
  });
</script>

<style scoped>
  @import './unDefenseModel.css';
  @import './fontEnhance.css';
  /* .model-container {
    width: 100%;
  }

  .model-content {
    width: 100%;
  }

  .model-title-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 2.5rem;
    border-bottom: 1px solid #e5e7eb;
    margin-bottom: 1rem;
  }

  .icon-title-legend {
    width: 0.25rem;
    height: 1.25rem;
    background: #3b82f6;
    border-radius: 1px;
  }

  .title-text {
    font-size: 1.125rem;
    font-weight: 500;
    color: #1f2937;
    flex: 1;
    margin-left: 0.5rem;
  }

  .close-box {
    width: 1.5rem;
    height: 1.5rem;
    cursor: pointer;
  }

  .content-box {
    margin-bottom: 1rem;
  }

  .btn-box {
    display: flex;
    justify-content: flex-end;
    gap: 1rem;
  } */
</style>
